<template>
  <el-card>
    <el-form inline :disabled="disabled">
      <el-form-item label="一级分类">
        <el-select
          class="m-2"
          placeholder="请选择"
          :model-value="categoryStore.category1Id"
          @update:model-value="category1IdChange"
        >
          <el-option
            v-for="item in categoryStore.category1List"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select
          class="m-2"
          placeholder="请选择"
          :model-value="categoryStore.category2Id"
          @update:model-value="category2IdChange"
        >
          <el-option
            v-for="item in categoryStore.category2List"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select
          class="m-2"
          placeholder="请选择"
          v-model="categoryStore.category3Id"
        >
          <el-option
            v-for="item in categoryStore.category3List"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "CategorySelector",
}
</script>

<script lang="ts" setup>
import { onMounted, defineProps, onBeforeMount } from "vue"
import { useCategoryStore } from "@/stores/categorySelector"
const categoryStore = useCategoryStore()
// 页面加载请求一级分类数据
onMounted(() => {
  categoryStore.getCategory1List()
})
// 当一级分类id发送变化触发的函数
const category1IdChange = async (category1Id: number) => {
  categoryStore.getCategory2List(category1Id)
}

// 当二级分类id发送变化触发的函数
const category2IdChange = async (category2Id: number) => {
  categoryStore.getCategory3List(category2Id)
}

// 申明接收
defineProps<{
  disabled: boolean
}>()
// 组件卸载时，清空仓库数据
onBeforeMount(() => {
  categoryStore.category1Id = undefined
  categoryStore.category2Id = undefined
  categoryStore.category3Id = undefined
  categoryStore.category1List = []
  categoryStore.category2List = []
  categoryStore.category3List = []
})
</script>

<style scoped></style>
